from setting import *
from bezier import *
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
# 敌人飞机


class EnemyPlane(pygame.sprite.Sprite):
    # 初始化敌人飞机
    def __init__(self):
        self._layer = 2
        self.groups = allgroup
        pygame.sprite.Sprite.__init__(self, self.groups)
        self.image = pygame.image.load('./images/enemy/enemy0.png')
        self.rect = self.image.get_rect()
        self.HP = 1
        #飞机的速度
        self.speed = 2
        self.x_speed = 0
        self.y_speed = 2
        #当采用路径时，输入的控制点
        self.points= []
        #飞机路径上的点 point(x,y)
        self.path_points = []
        #飞机正常方式
        self.path_type = 'normal'
        #飞机用路径描述的最大的点,当前点
        self.max_point = 1000
        self.current_point = 0

    # 设置飞机位置
    def set_pos(self, x, y):

        self.rect.x = x
        self.rect.y = y

    def set_bezier_path(self, points):
        self.path_type = 'bezier'
        self.points = points
        for v in range(0, self.max_point+1):
            t = v / self.max_point
            self.path_points.append(bezier(self.points, t))
            
    def set_BSpline_path(self,points):
        self.path_type = 'BSpline'
        self.points = points
        data = np.array(points)
        tck,u = interpolate.splprep(data.transpose(), s=0)
        t = 1 / self.max_point
        unew = np.arange(0, 1.01, t)
        out = interpolate.splev(unew, tck)
        self.path_points=out


    def update(self):
        """ 
        更新位置
            计算位置，精灵组自动调用
            超出屏幕，自毁
        """
        if self.path_type == 'bezier':
            if self.current_point == self.max_point:
                self.current_point = 0

            # print(self.path_points[self.current_point][0])
            self.rect.x = self.path_points[self.current_point][0]
            self.rect.y = self.path_points[self.current_point][1]
            self.current_point += 1
        elif self.path_type == 'BSpline':
            if self.current_point == self.max_point:
                self.current_point = 0
            self.rect.x = self.path_points[0][self.current_point]
            self.rect.y = self.path_points[1][self.current_point]
            self.current_point += 1
        else:
            self.rect.x += self.x_speed
            self.rect.y += self.y_speed
        if self.HP <= 0:
            self.kill()
        if not self.rect.colliderect(SCENERECT):
            self.kill()
